<?php
namespace control;
// 资产折旧汇总

class assetTotalClass extends adIndexClass
{
    private const page = 'assetTotal'; # 权限
    private const table = 'asset'; # 数据表
    private const title = '资产折旧汇总';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(['name' => 'time', 'laydate' => ['range' => '~', 'type' => 'month'], 'value' => date('Y-m') . ' ~ ' . date('Y-m')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }


    /*固定资产列表*/
    public function homeSearch(): bool|string
    {
        $workFlow = '按使用部门';
        //全等查询数组
        $equal = [
            'coid' => self::$coid
        ];
        $like = [

        ];

        //生成查询语句
        $where = search([
            "=" => $equal,
            "like" => $like,
        ]);
        $arr = $this->post('time') ? explode(' ~ ', $this->post('time')) : [date('Y-m'), date('Y-m')];
        $startMonth = trim($arr[0]);
        $initDate = $startMonth . '-01';
        $endDate = $arr[1].'-'.sprintf('%02d',date('t',strtotime($arr[1])));
        $page = $this->page(["table" => self::table, 'field' => 'distinct departmentId', "where" => $where, "order" => "any_value(time) desc"]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $_SESSION[self::page]['time'] = $this->post('time')?:date('Y-m').' ~ '.date('Y-m');
        //获取表头
        $tr = [];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = [
                departmentClass::getTypeName($array['departmentId']),
                $this->salaryInit($initDate,$workFlow,$array['departmentId']),
                $this->salaryAdd($initDate,$endDate,$workFlow,$array['departmentId']),
                $this->salaryDec($initDate,$endDate,$workFlow,$array['departmentId']),
                $this->salaryEnd($initDate,$endDate,$workFlow,$array['departmentId']),
                $this->depreciationInit($initDate,$workFlow,$array['departmentId']),
                $this->depreciationAdd($initDate,$endDate,$workFlow,$array['departmentId']),
                $this->depreciationDec($initDate,$endDate,$workFlow,$array['departmentId']),
                $this->depreciationEnd($initDate,$endDate,$workFlow,$array['departmentId']),
                round($this->salaryInit($initDate,$workFlow,$array['departmentId'])-$this->depreciationInit($initDate,$workFlow,$array['departmentId']),2),
                round( $this->salaryAdd($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationAdd($initDate,$endDate,$workFlow,$array['departmentId']),2),
                round($this->salaryDec($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationDec($initDate,$endDate,$workFlow,$array['departmentId']),2),
                round($this->salaryEnd($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationEnd($initDate,$endDate,$workFlow,$array['departmentId']),2),
            ];
        }
        $list = $this->tableMany(array("tr" => $tr, 'thead' => false));
        $html = <<<eof
 <table class="tableMany">
                    <thead>
                        <tr><td rowspan="2" class="center" style="vertical-align:middle">部门</td><td colspan="4" class="center">资产原值</td><td colspan="4" class="center">累计折旧</td><td colspan="4" class="center">资产净值</td></tr>
                        <tr><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td></tr>
                    </thead>
                    <tbody>
                       $list
                    </tbody>
                </table>
eof;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 条件组装
     * @param $workFlow
     * @param $targetId
     * @return string
     */
    private function sqlWhere($workFlow,$targetId): string
    {
        if ($workFlow =='按资产类别'){
//            $idArr = assetCatalogClass::getAllChildTypeId($targetId);
//            $where = " and acid in ('".implode("','",$idArr)."')";
            $where = " and acid = '$targetId'";
        }else{
            $where = " and departmentId = '$targetId'";
        }
        return $where;
    }
    /**
     * 累计折旧--期初
     */
    private function depreciationInit($startDate,$workFlow,$targetId): float
    {
        $finishDate =date('Y-m-d',strtotime("-1 day",strtotime($startDate)));
        $where = $this->sqlWhere($workFlow,$targetId);
        $all = find(array('table'=>'asset','where'=>"coid = '".self::$coid."' and purchaseDate < '$startDate' and id not in (select atid from asset_cut_detail as a join asset_cut as b on a.orderId = b.id where b.state = '已通过' and b.date < '$startDate' and a.coid = '".self::$coid."')".$where));
        $money = 0;
        foreach ($all['array'] as $array){
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$finishDate);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio,$array['purchaseDate'],$finishDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $money += assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$finishDate);
        }
        return round($money,2);
    }

    /**
     * 累计折旧--本期增加
     */
    private function depreciationAdd($startDate,$endDate,$workFlow,$targetId): float
    {
        $where = $this->sqlWhere($workFlow,$targetId);
        $all =  find(array('table' => 'asset', 'where' => "coid = '" . self::$coid . "' and purchaseDate >= '$startDate' and purchaseDate <= '$endDate'".$where));
        $initMoney=$finisMoney = 0;
        foreach ($all['array'] as $array){
            //期初
            $initDate =date('Y-m-d',strtotime("-1 day",strtotime($startDate)));
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$initDate);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio,$array['purchaseDate'],$initDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $initMoney+= assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$initDate);
            //期末
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$endDate);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio,$array['purchaseDate'],$endDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $finisMoney+= assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$endDate);
        }
        return round($finisMoney-$initMoney,2);
    }
    /**
     * 累计折旧--本期减少
     */
    private function depreciationDec($startDate,$endDate,$workFlow,$targetId): float
    {
        $where = $this->sqlWhere($workFlow,$targetId);
        $all =  find(array('table' => 'asset', 'where' => "coid = '" . self::$coid . "' and purchaseDate >= '$startDate' and purchaseDate <= '$endDate' and id in (select atid from asset_cut_detail as a join asset_cut as b on a.orderId = b.id where b.state = '已通过' and b.date >= '$startDate' and b.date <='$endDate' and a.coid = '".self::$coid."')".$where));
        $initMoney=$finisMoney = 0;
        foreach ($all['array'] as $array){
            //期初
            $initDate =date('Y-m-d',strtotime("-1 day",strtotime($startDate)));
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$initDate);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio,$array['purchaseDate'],$initDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $initMoney+= assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$initDate);
            //期末
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$endDate);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio,$array['purchaseDate'],$endDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $finisMoney+= assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$endDate);
        }
        return round($finisMoney-$initMoney,2);
    }
    /**
     * 累计折旧--期末
     */
    private function depreciationEnd($startDate,$endDate,$workFlow,$targetId): float
    {
        return round($this->depreciationInit($startDate,$workFlow,$targetId)+$this->depreciationAdd($startDate,$endDate,$workFlow,$targetId)-$this->depreciationDec($startDate,$endDate,$workFlow,$targetId),2);
    }


    /**
     * 资金原值--期初
     */
    private function salaryInit($startDate,$workFlow,$targetId): float
    {
        $where = $this->sqlWhere($workFlow,$targetId);
        $money =  find(array('table' => 'asset', 'where' => "coid = '" . self::$coid . "' and purchaseDate < '$startDate'".$where, 'sum' => "purchaseMoney"));
        $cutMoney = find(array('table' => 'asset_cut as a join asset_cut_detail as b on a.id = b.orderId join asset as c on b.atid = c.id', 'single' => "a.coid = '" . self::$coid . "' and a.date < '$startDate'".$where, 'field' => "ifnull(sum(c.purchaseMoney),0) as total"))['total'];
        return round($money-$cutMoney,2);
    }
    /**
     * 资金原值--本期增加
     */
    private function salaryAdd($startDate,$endDate,$workFlow,$targetId): float
    {
        $where = $this->sqlWhere($workFlow,$targetId);
        return find(array('table' => 'asset', 'where' => "coid = '" . self::$coid . "' and purchaseDate >= '$startDate' and purchaseDate <= '$endDate'".$where, 'sum' => "purchaseMoney"));
    }
    /**
     * 资金原值--本期减少
     */
    private function salaryDec($startDate,$endDate,$workFlow,$targetId): float
    {
        $where = $this->sqlWhere($workFlow,$targetId);
        return find(array('table' => 'asset_cut as a join asset_cut_detail as b on a.id = b.orderId join asset as c on b.atid = c.id', 'single' => "a.coid = '" . self::$coid . "' and a.date >= '$startDate' and a.date <= '$endDate'".$where, 'field' => "ifnull(sum(c.purchaseMoney),0) as total"))['total'];
    }

    /**
     * 资金原值--期末
     */
    private function salaryEnd($startDate,$endDate,$workFlow,$targetId): float
    {
        return round($this->salaryInit($startDate,$workFlow,$targetId)+$this->salaryAdd($startDate,$endDate,$workFlow,$targetId)-$this->salaryDec($startDate,$endDate,$workFlow,$targetId),2);
    }

    /*列表页-查询条件*/
    public function waitReportOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(['name' => 'time', 'laydate' => ['range' => '~', 'type' => 'month'], 'value' => date('Y-m') . ' ~ ' . date('Y-m')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function waitReport()
    {
        $html = $this->waitReportOptions(false);
        //控件
        $button = "";
        if ($this->power('assetTotalType', "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportDataT' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function waitReportSearch(): bool|string
    {
        $workFlow = '按资产类别';
        //全等查询数组
        $equal = [
            'coid' => self::$coid
        ];
        $like = [

        ];

        //生成查询语句
        $where = search([
            "=" => $equal,
            "like" => $like,
        ]);
        $arr = $this->post('time') ? explode(' ~ ', $this->post('time')) : [date('Y-m'), date('Y-m')];
        $startMonth = trim($arr[0]);
        $initDate = $startMonth . '-01';
        $endDate = $arr[1].'-'.sprintf('%02d',date('t',strtotime($arr[1])));
        $page = $this->page(["table" => self::table, 'field' => 'distinct acid', "where" => $where, "order" => "any_value(time) desc"]);
        $_SESSION[self::page]['sql2'] = $page['fullSql'];
        $_SESSION[self::page]['time2'] = $this->post('time')?:date('Y-m').' ~ '.date('Y-m');
        //获取表头
        $tr = [];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = [
                assetCatalogClass::getCatalogName($array['acid']),
                $this->salaryInit($initDate,$workFlow,$array['acid']),
                $this->salaryAdd($initDate,$endDate,$workFlow,$array['acid']),
                $this->salaryDec($initDate,$endDate,$workFlow,$array['acid']),
                $this->salaryEnd($initDate,$endDate,$workFlow,$array['acid']),
                $this->depreciationInit($initDate,$workFlow,$array['acid']),
                $this->depreciationAdd($initDate,$endDate,$workFlow,$array['acid']),
                $this->depreciationDec($initDate,$endDate,$workFlow,$array['acid']),
                $this->depreciationEnd($initDate,$endDate,$workFlow,$array['acid']),
                round($this->salaryInit($initDate,$workFlow,$array['acid'])-$this->depreciationInit($initDate,$workFlow,$array['acid']),2),
                round( $this->salaryAdd($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationAdd($initDate,$endDate,$workFlow,$array['acid']),2),
                round($this->salaryDec($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationDec($initDate,$endDate,$workFlow,$array['acid']),2),
                round($this->salaryEnd($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationEnd($initDate,$endDate,$workFlow,$array['acid']),2),
            ];
        }
        $list = $this->tableMany(array("tr" => $tr, 'thead' => false));
        $html = <<<eof
 <table class="tableMany">
                    <thead>
                        <tr><td rowspan="2" class="center" style="vertical-align:middle">类别</td><td colspan="4" class="center">资产原值</td><td colspan="4" class="center">累计折旧</td><td colspan="4" class="center">资产净值</td></tr>
                        <tr><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td><td>期初数</td><td>本期增加</td><td>本期减少</td><td>期末数</td></tr>
                    </thead>
                    <tbody>
                       $list
                    </tbody>
                </table>
eof;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     * @return void
     */
    public function exportDataT()
    {
        if (!$this->power('assetTotalType', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $workFlow = '按资产类别';
            $sql= $_SESSION[self::page]['sql2'];
            $arr = explode(' ~ ',$_SESSION[self::page]['time2']);
            $startMonth = trim($arr[0]);
            $initDate = $startMonth . '-01';
            $endDate = $arr[1].'-'.sprintf('%02d',date('t',strtotime($arr[1])));
            $title = ['部门', '资产原值期初数', '资产原值本期增加', '资产原值本期减少', '资产原值期末数', '累计折旧期初数', '累计折旧本期增加', '累计折旧本期减少', '累计折旧期末数',
                '资产净值期初数', '资产净值本期增加', '资产净值本期减少', '资产净值期末数'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $tr[] = [
                        assetCatalogClass::getCatalogName($array['acid']),
                        $this->salaryInit($initDate,$workFlow,$array['acid']),
                        $this->salaryAdd($initDate,$endDate,$workFlow,$array['acid']),
                        $this->salaryDec($initDate,$endDate,$workFlow,$array['acid']),
                        $this->salaryEnd($initDate,$endDate,$workFlow,$array['acid']),
                        $this->depreciationInit($initDate,$workFlow,$array['acid']),
                        $this->depreciationAdd($initDate,$endDate,$workFlow,$array['acid']),
                        $this->depreciationDec($initDate,$endDate,$workFlow,$array['acid']),
                        $this->depreciationEnd($initDate,$endDate,$workFlow,$array['acid']),
                        round($this->salaryInit($initDate,$workFlow,$array['acid'])-$this->depreciationInit($initDate,$workFlow,$array['acid']),2),
                        round( $this->salaryAdd($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationAdd($initDate,$endDate,$workFlow,$array['acid']),2),
                        round($this->salaryDec($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationDec($initDate,$endDate,$workFlow,$array['acid']),2),
                        round($this->salaryEnd($initDate,$endDate,$workFlow,$array['acid'])-$this->depreciationEnd($initDate,$endDate,$workFlow,$array['acid']),2),
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => 'assetTotalType', "text" => $text]);
            $this->excelOut($title, $tr, self::title . "(按资产类别).xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 导出
     * @return void
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $workFlow = '按使用部门';
            $sql= $_SESSION[self::page]['sql'];
            $arr = explode(' ~ ',$_SESSION[self::page]['time']);
            $startMonth = trim($arr[0]);
            $initDate = $startMonth . '-01';
            $endDate = $arr[1].'-'.sprintf('%02d',date('t',strtotime($arr[1])));
            $title = ['部门', '资产原值期初数', '资产原值本期增加', '资产原值本期减少', '资产原值期末数', '累计折旧期初数', '累计折旧本期增加', '累计折旧本期减少', '累计折旧期末数',
                '资产净值期初数', '资产净值本期增加', '资产净值本期减少', '资产净值期末数'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $tr[] = [
                        departmentClass::getTypeName($array['departmentId']),
                        $this->salaryInit($initDate,$workFlow,$array['departmentId']),
                        $this->salaryAdd($initDate,$endDate,$workFlow,$array['departmentId']),
                        $this->salaryDec($initDate,$endDate,$workFlow,$array['departmentId']),
                        $this->salaryEnd($initDate,$endDate,$workFlow,$array['departmentId']),
                        $this->depreciationInit($initDate,$workFlow,$array['departmentId']),
                        $this->depreciationAdd($initDate,$endDate,$workFlow,$array['departmentId']),
                        $this->depreciationDec($initDate,$endDate,$workFlow,$array['departmentId']),
                        $this->depreciationEnd($initDate,$endDate,$workFlow,$array['departmentId']),
                        round($this->salaryInit($initDate,$workFlow,$array['departmentId'])-$this->depreciationInit($initDate,$workFlow,$array['departmentId']),2),
                        round( $this->salaryAdd($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationAdd($initDate,$endDate,$workFlow,$array['departmentId']),2),
                        round($this->salaryDec($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationDec($initDate,$endDate,$workFlow,$array['departmentId']),2),
                        round($this->salaryEnd($initDate,$endDate,$workFlow,$array['departmentId'])-$this->depreciationEnd($initDate,$endDate,$workFlow,$array['departmentId']),2),
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . "(按部门).xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
